import { Button } from 'antd';
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import {Student} from "../services/types.ts";

interface ExportButtonProps {
    data: Student[]; // 要导出的数据数组
    filename?: string; // 默认文件名
    sheetName?: string; // 工作表名称
}

export function ExportButton({
                                 data,
                                 filename = 'export.xlsx',
                                 sheetName = 'Sheet1'
                             }: ExportButtonProps) {
    const handleExport = () => {
        // 1. 创建工作簿
        const wb = XLSX.utils.book_new();

        // 2. 将JSON数据转换为工作表
        // const ws = XLSX.utils.json_to_sheet(data);
        const ws =XLSX.utils.aoa_to_sheet([["姓名","学号","生日","班级"],...data.map(item=>[item.name,item.student_id.toString(),item.birthday,item.class])],)
        // 3. 将工作表添加到工作簿
        XLSX.utils.book_append_sheet(wb, ws, sheetName);

        // 4. 生成Excel文件buffer
        const excelBuffer = XLSX.write(wb, {
            bookType: 'xlsx',
            type: 'array'
        });

        // 5. 触发下载
        saveAs(
            new Blob([excelBuffer], { type: 'application/octet-stream' }),
            filename
        );
    };

    return (
        <Button type="primary" onClick={handleExport}>
            导出Excel
        </Button>
    );
}
